namespace Mytodotodaylist.DataAccess
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Core.Events;
    using FluentAdoDotNet;

    public class EventRepositoryImpl : IEventRepository
    {
        public List<Event> GetAll()
        {
            const string sql = @"SELECT Id, Name, Date, Frequency FROM Events";

            return new FluentCommand<Event>(sql)
                .SetMap(EventMap)
                .AsList()
                .ToList();
        }

        public Event GetById(Guid eventId)
        {
            const string sql = @"SELECT Id, Name, Date, Frequency FROM Events where Id=@Id";

            return new FluentCommand<Event>(sql)
                .AddGuid("Id", eventId)
                .SetMap(EventMap)
                .AsSingle();
        }

        public void Add(Event theEvent)
        {
            const string sql = @"INSERT INTO Events values (@Id, @Name, @Date, @Frequency)";
            new FluentCommand<string>(sql)
                .AddGuid("Id", theEvent.Id)
                .AddString("Name", theEvent.Name)
                .AddDateTime("Date", theEvent.Date)
                .AddInt("Frequency", (int)theEvent.Frequency)
                .AsNonQuery();
        }

        public void Update(Event theEvent)
        {
            const string sql = @"UPDATE Events SET Name = @Name, Date = @Date, Frequency = @Frequency WHERE Id=@Id";
            
            new FluentCommand<string>(sql)
                .AddGuid("Id", theEvent.Id)
                .AddString("Name", theEvent.Name)
                .AddDateTime("Date", theEvent.Date)
                .AddInt("Frequency", (int)theEvent.Frequency)
                .AsNonQuery();
        }

        public void Delete(Guid eventId)
        {
            const string sql = "DELETE FROM Events WHERE Id = @Id";
            new FluentCommand<Event>(sql)
                .AddGuid("Id", eventId)
                .AsNonQuery();
        }

        private Event EventMap(DataReader reader)
        {
            return new Event()
                       {
                           Id = reader.GetGuid("Id"),
                           Name = reader.GetString("Name"),
                           Date = reader.GetDateTime("Date"),
                           Frequency = (Periodicity)reader.GetInt("Frequency")
                       };
        }

    }
}